package yur.wedding.modules.sys.service.impl;


import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


import org.springframework.transaction.annotation.Transactional;
import yur.wedding.common.annotation.DataFilter;
import yur.wedding.common.utils.Constant;
import yur.wedding.common.utils.Query;

import yur.wedding.modules.sys.dao.SysUserDao;

import yur.wedding.modules.sys.entity.SysDeptEntity;

import yur.wedding.modules.sys.entity.SysUserEntity;
import yur.wedding.modules.sys.service.SysDeptService;


import yur.wedding.modules.sys.service.SysUserRoleService;
import yur.wedding.modules.sys.service.SysUserService;
import yur.wedding.modules.sys.shiro.ShiroUtils;
import yur.wedding.utils.PageUtils;
import yur.wedding.utils.R;

import javax.annotation.Resource;


@Service("sysUserService")
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUserEntity> implements SysUserService {

    @Resource
    private SysDeptService sysDeptService;

    @Resource
    SysUserRoleService sysUserRoleService;


    @Override
    @DataFilter(subDept = true, user = false)
    public PageUtils queryPage(Map<String, Object> params) {
        String username = (String) params.get("username");
        Long depid = (Long) params.get("deptId");
        String workcoke = (String) params.get("workcoke");
        IPage<SysUserEntity> page = this.page(
                new Query<SysUserEntity>().getPage(params),
                new QueryWrapper<SysUserEntity>()
                        .like(StringUtils.isNotBlank(username), "username", username)
                        //.like(StringUtils.isEmpty(depid), "deptId", depid)
                        .apply(params.get(Constant.SQL_FILTER) != null, (String) params.get(Constant.SQL_FILTER))
        );
        for (SysUserEntity userentity : page.getRecords()) {
            if (userentity != null) {
                SysDeptEntity byId = sysDeptService.getById(userentity.getDeptId());
                userentity.setDeptName(byId.getName());

            }


        }

        return new PageUtils(page);
    }

    /**
     * 添加用户
     *
     * @param sysUser
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveUser(SysUserEntity sysUser) {
        sysUser.setCreateTime(new Date());
        //sha256 加密
        String sha256 = RandomStringUtils.randomAlphanumeric(20);
        sysUser.setSalt(sha256);
        String password = ShiroUtils.sha256(sysUser.getPassword(), sha256);
        sysUser.setPassword(password);

        String firstChar = toFirstChar(sysUser.getLastName());
        sysUser.setPinYinLastName(firstChar);

        SysUserEntity user01 = baseMapper.selectWorkCode(sysUser.getWorkCode());
        if (user01 != null) {
            return false;
        } else {
            this.save(sysUser);
            //添加  用户与角色 的关系
            if (sysUser.getRoleIdList().size() > 0) {
                sysUserRoleService.saveOrUpdate(sysUser.getUserId(), sysUser.getRoleIdList());
            }
            return true;
        }


    }

    /**
     * 修改用户
     *
     * @param sysUser
     */
    @Override
    public void updateUser(SysUserEntity sysUser) {
        if (StringUtils.isBlank(sysUser.getPassword())) {
            sysUser.setPassword(null);
        } else {
            SysUserEntity userEntity = this.getById(sysUser.getUserId());

            sysUser.setPassword(ShiroUtils.sha256(sysUser.getPassword(), userEntity.getSalt()));
        }
        this.updateById(sysUser);
        if (sysUser.getRoleIdList().size() > 0) {
            //修改角色
            sysUserRoleService.saveOrUpdate(sysUser.getUserId(), sysUser.getRoleIdList());
        }

    }


    /**
     * 获取字符串拼音的第一个字母
     *
     * @param chinese
     * @return
     */
    public static String toFirstChar(String chinese) {
        String pinyinStr = "";
        //转为单个字符
        char[] newChar = chinese.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < newChar.length; i++) {
            if (newChar[i] > 128) {
                try {
                    pinyinStr += PinyinHelper.toHanyuPinyinStringArray(newChar[i], defaultFormat)[0].charAt(0);
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                pinyinStr += newChar[i];
            }
        }
        return pinyinStr;
    }

    /**
     * 查询角色下面用户
     *
     * @param params
     * @return
     */
    @Override
    @DataFilter(subDept = true, user = false)
    public PageUtils queryroleUserPage(Map<String, Object> params) {
        List<Long> user_id = (List<Long>) params.get("userId");
        IPage<SysUserEntity> page = this.page(
                new Query<SysUserEntity>().getPage(params),
                new QueryWrapper<SysUserEntity>()
                        //in  以与查询角色下面的用户
                        .in(user_id.size() > 0, "user_id", user_id)
                        .apply(params.get(Constant.SQL_FILTER) != null, (String) params.get(Constant.SQL_FILTER))
        );
        for (SysUserEntity userentity : page.getRecords()) {
            if (userentity != null) {
                SysDeptEntity byId = sysDeptService.getById(userentity.getDeptId());
                userentity.setDeptName(byId.getName());
            }

        }

        return new PageUtils(page);
    }

    /**
     * 角色模块  模糊查询用户
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils queryRoleListPage(Map<String, Object> params) {
        String lastname = (String) params.get("lastname_s");
        String workcoke = (String) params.get("workcoke_s");

        QueryWrapper<SysUserEntity> wrapper = new QueryWrapper<>();

        wrapper.like("work_code", workcoke).and(i -> i.like("last_name", lastname).or().like("pin_yin_last_name", lastname));
        // wrapper.last(StringUtils.isNotBlank(username),"WHERE concat(username, ',', work_code, ',', pin_yin_last_name) LIKE %"+username+"%");
        wrapper.apply(params.get(Constant.SQL_FILTER) != null, (String) params.get(Constant.SQL_FILTER));
        IPage<SysUserEntity> page = this.page(
                new Query<SysUserEntity>().getPage(params), wrapper
        );
        for (SysUserEntity userentity : page.getRecords()) {
            if (userentity != null) {
                SysDeptEntity byId = sysDeptService.getById(userentity.getDeptId());
                userentity.setDeptName(byId.getName());
            }

        }

        return new PageUtils(page);
    }

    /**
     * 更加 部门 或角色 查询用户 共用
     *
     * @return
     */
    @Override
    public List<Long> queryDeptRoleListPage(Long id, String type) {

        if ("dept_id".equals(type)) {
            return baseMapper.queryDeptListPage(id);
        } else if ("role_id".equals(type)) {

            return sysUserRoleService.roleuserlist(id);
        }
        return null;

    }

    private static String sun;

    @Override
    public R addUserList(String fileName, InputStream is) {
        sun = "";

        List<SysUserEntity> upload = upload(fileName, is);
        this.saveBatch(upload);
        if ("".equals(sun)) {
            return R.ok().put("msg", "成功数:"+upload.size());
        }

        return R.ok().put("msg", "成功数:"+upload.size()+"。异常:"+ sun);
    }


    public List<SysUserEntity> upload(String fileName, InputStream is) {
        List<SysUserEntity> piLList = new ArrayList<>();
        Set sett = new HashSet();//判断是否存在有重复的
        try {
            Workbook workbook = new HSSFWorkbook(is);
            int number = workbook.getNumberOfSheets(); // 获取sheet值
            for (int i = 0; i < number; i++) {
                Sheet sheet = workbook.getSheetAt(i); // 获取表格页码
                if (sheet != null) {
                    int rowNum = sheet.getLastRowNum(); // 获取该页表共有多少行
                    for (int j = 1; j <= rowNum; j++) {  // 一般来说第一行是标题,所以第二行开始读取
                        Row row = sheet.getRow(j); // 获取表格行
                        SysUserEntity user = new SysUserEntity();

                        row.getCell(0).setCellType(Cell.CELL_TYPE_STRING); // 将该单元格获取出来的值设为String类型
                        user.setLastName(row.getCell(0).getStringCellValue());
                        if (row.getCell(0).getStringCellValue() == null) {
                            if (sun == null) {
                                sun = "第" + j + "行数据不完整";
                            } else {
                                sun += ",第" + j + "行数据不完整";
                            }
                            continue;
                        }

                        row.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
                        user.setUsername(row.getCell(1).getStringCellValue());
                        if (row.getCell(1).getStringCellValue() == null) {
                            if ("".equals(sun)) {
                                sun = "第" + j + "行数据不完整";
                            } else {
                                sun += ",第" + j + "行数据不完整";
                            }
                            continue;
                        } else {
                            if (sett.add(row.getCell(1).getStringCellValue())) {
                                SysUserEntity user02 = baseMapper.selectUserName(row.getCell(1).getStringCellValue());
                                if (user02 != null) {
                                    if ("".equals(sun)) {
                                        sun = "第" + j + "行数据已存在";
                                    } else {
                                        sun += ",第" + j + "行数据已存在";
                                    }
                                    continue;
                                }
                            } else {
                                if ("".equals(sun)) {
                                    sun = "第" + j + "行存在重复数据";
                                } else {
                                    sun += ",第" + j + "行存在重复数据";
                                }
                                continue;
                            }
                        }

                        row.getCell(2).setCellType(Cell.CELL_TYPE_STRING);
                        user.setPassword(row.getCell(2).getStringCellValue());
                        if (row.getCell(2).getStringCellValue() == null) {
                            if (sun == null) {
                                sun = "第" + j + "行数据不完整";
                            } else {
                                sun += ",第" + j + "行数据不完整";
                            }
                            continue;
                        }

                        //唯一  编号
                        row.getCell(3).setCellType(Cell.CELL_TYPE_STRING);
                        user.setWorkCode(row.getCell(3).getStringCellValue());

                        if (row.getCell(3).getStringCellValue() == null) {
                            if ("".equals(sun)) {
                                sun = "第" + j + "行数据不完整";
                            } else {
                                sun += ",第" + j + "行数据不完整";
                            }
                            continue;
                        } else {
                            if (sett.add(row.getCell(3).getStringCellValue())) {
                                SysUserEntity user01 = baseMapper.selectWorkCode(row.getCell(3).getStringCellValue());
                                if (user01 != null) {
                                    if ("".equals(sun)) {
                                        sun = "第" + j + "行数据已存在";
                                    } else {
                                        sun += ",第" + j + "行数据已存在";
                                    }
                                    continue;
                                }
                            } else {
                                if ("".equals(sun)) {
                                    sun = "第" + j + "行存在重复数据";
                                } else {
                                    sun += ",第" + j + "行存在重复数据";
                                }
                                continue;
                            }
                        }
                        row.getCell(4).setCellType(Cell.CELL_TYPE_STRING);
                        user.setSalt("男".equals(row.getCell(4).getStringCellValue()) ? "0" : "1");
                        if (row.getCell(4).getStringCellValue() == null) {
                            if ("".equals(sun)) {
                                sun = "第" + j + "行数据不完整";
                            } else {
                                sun += ",第" + j + "行数据不完整";
                            }
                            continue;
                        }

                        row.getCell(5).setCellType(Cell.CELL_TYPE_STRING);
                        user.setDeptId(Long.parseLong(row.getCell(5).getStringCellValue()));
                        if (row.getCell(5).getStringCellValue() == null) {
                            if ("".equals(sun)) {
                                sun = "第" + j + "行数据不完整";
                            } else {
                                sun += ",第" + j + "行数据不完整";
                            }
                            continue;
                        }

                        row.getCell(6).setCellType(Cell.CELL_TYPE_STRING);
                        user.setEmail(row.getCell(6).getStringCellValue());
                        row.getCell(7).setCellType(Cell.CELL_TYPE_STRING);
                        user.setMobile(row.getCell(7).getStringCellValue());

                        String sha256 = RandomStringUtils.randomAlphanumeric(20);
                        user.setSalt(sha256);
                        String password = ShiroUtils.sha256(user.getPassword(), sha256);
                        user.setPassword(password);
                        String firstChar = toFirstChar(user.getLastName());
                        user.setPinYinLastName(firstChar);
                        user.setCreateTime(new Date());
                        user.setStatus(1);
                        piLList.add(user);
                    }
                }
            }
        } catch (Exception e) {

        }


        return piLList;
    }


}
